<template>
    <el-container style="margin-left: 100px">
        <el-header style="text-align: center">
            <privateChat
                style="height: 50px;width:auto"
                :username="GroupName"
                :a="a"
                :b="b"
                :c="c"
                :d="d"
            />
        </el-header>
        <div class="main-container">
            <!-- 左侧群组列表 -->
            <div class="chat-sidebar">
                <div class="sidebar-header">
                    <h3>我的群组</h3>
                    <div class="sidebar-actions">
                        <el-button
                            type="primary"
                            size="small"
                            icon="el-icon-plus"
                            circle
                            @click="createGroup"
                            title="创建群聊"
                        ></el-button>
                        <el-button
                            type="success"
                            size="small"
                            icon="el-icon-search"
                            circle
                            @click="joinGroup"
                            title="加入群聊"
                        ></el-button>
                    </div>
                </div>
                
                <div class="group-list">
                    <router-link
                        to="/Main/littleGroupChats/chat"
                        class="group-item"
                        v-for="count in grouplist"
                        :class="{'active-group': active && active.groupId === count.groupId}"
                        :key="count.groupId"
                        @click.native="checkChat(count)"
                    >
                        <el-avatar :size="40" :src="count.groupPicture" class="group-avatar"></el-avatar>
                        <div class="group-item-info">
                            <div class="group-name">{{count.groupName}}</div>
                            <div class="group-status">
                                <span class="status-dot online"></span>
                                <span class="status-text">在线</span>
                            </div>
                        </div>
                    </router-link>
                    
                    <div v-if="grouplist.length === 0" class="empty-groups">
                        <i class="el-icon-chat-dot-round"></i>
                        <p>暂无群组，请创建或加入群组</p>
                    </div>
                </div>
            </div>
            
            <!-- 主聊天内容 -->
            <div class="chat-main">
                <router-view style="width: 100%; height: 100%;"/>
            </div>
            
            <!-- 右侧群组信息 -->
            <div class="chat-info">
                <div class="info-header">
                    <h3>群组信息</h3>
                </div>
                
                <div v-if="active" class="group-info-content">
                    <div class="group-profile">
                        <el-avatar :size="80" :src="active.groupPicture" class="group-avatar-large"></el-avatar>
                        <h4 class="group-title">{{ active.groupName }}</h4>
                        <div class="group-id">群 ID: {{ active.groupId }}</div>
                        <div class="group-owner">群主: {{ active.groupBuilder }}</div>
                    </div>
                    
                    <el-divider content-position="center">群组操作</el-divider>
                    
                    <div class="group-actions">
                        <el-button type="danger" plain @click="quitGroup(active.groupId)">
                            <i class="el-icon-switch-button"></i> 退出群聊
                        </el-button>
                    </div>
                </div>
                
                <div v-else class="empty-info">
                    <i class="el-icon-info-circle"></i>
                    <p>请从左侧选择群组</p>
                </div>
            </div>
        </div>

        <!-- 创建群聊弹窗 -->
        <el-dialog
            title="创建新群聊"
            :visible.sync="createDialogVisible"
            width="30%"
            @close="resetForm('createGroupForm')">
            <el-form
                :model="createGroupForm"
                :rules="createGroupRules"
                ref="createGroupForm"
                label-width="100px">
                <el-form-item label="群组名称" prop="groupName">
                    <el-input v-model="createGroupForm.groupName"></el-input>
                </el-form-item>

                <el-form-item label="群组头像" prop="picture">
                    <el-upload
                        class="avatar-uploader"
                        action=""
                        :show-file-list="false"
                        :on-change="handleAvatarChange">
                        <img v-if="createGroupForm.pictureUrl" :src="createGroupForm.pictureUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="createDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitCreateGroup">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 加入群聊弹窗 -->
        <el-dialog
            title="加入群聊"
            :visible.sync="joinDialogVisible"
            width="50%"
            class="join-dialog"
            @close="resetSearch">
            <el-form>
                <el-form-item prop="searchGroupName">
                    <el-input
                        v-model="searchGroupId"
                        placeholder="输入群组ID进行搜索"
                        clearable
                        @clear="resetSearch">
                        <el-button slot="append" icon="el-icon-search" @click="searchGroups"></el-button>
                    </el-input>
                </el-form-item>
            </el-form>

            <div v-if="searchLoading" class="loading-container">
                <i class="el-icon-loading" style="font-size: 30px;"></i>
                <p>搜索中...</p>
            </div>

            <template v-else>
                <div v-if="searchGroup" class="group-search-result">
                    <div class="group-item-search">
                        <el-avatar :size="60" :src="searchGroup.groupPicture || defaultAvatar"></el-avatar>
                        <div class="group-info-search">
                            <h4>{{ searchGroup.groupName }}</h4>
                            <p>群主: {{ searchGroup.groupBuilder }}</p>
                            <p>群号: {{ searchGroup.groupId }}</p>
                        </div>
                        <el-button
                            type="primary"
                            class="join-btn"
                            @click="handleJoinGroup(searchGroup.groupId)"
                            :disabled="isGroupJoined(searchGroup.groupId)">
                            {{ isGroupJoined(searchGroup.groupId) ? '已加入' : '加入群组' }}
                        </el-button>
                    </div>
                </div>

                <div v-else-if="hasSearched" class="empty-search-result">
                    <i class="el-icon-search"></i>
                    <p>没有找到匹配的群组</p>
                </div>

                <div v-else class="empty-search-result">
                    <i class="el-icon-search"></i>
                    <p>请输入群组ID进行搜索</p>
                </div>
            </template>

            <span slot="footer" class="dialog-footer">
                <el-button @click="joinDialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </el-container>
</template>

<script>
import PrivateChat from "@/components/privateChat.vue";
import {createGroup, getGroupList, joinGroup, outGroup, searchGroupo} from "@/api/api";

export default {
    components: {
        PrivateChat
    },
    data() {
        return {
            a:"群",
            b:"组",
            c:"聊",
            d:"天",
            GroupName:"           ",
            grouplist: [],//已加入群聊列表
            searchGroup: null,
            active: null,
            loading: false,
            createDialogVisible: false,
            joinDialogVisible: false,
            searchGroupId: '',
            searchLoading: false,
            hasSearched: false,
            createGroupForm: {
                groupName: '',
                picture: null,
                pictureUrl: ''
            },
            createGroupRules: {
                groupName: [
                    { required: true, message: '请输入群组名称', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                picture: [
                    { validator: (rule, value, callback) => {
                            if (!this.createGroupForm.picture) {
                                callback(new Error('请上传群组头像'));
                            } else {
                                callback();
                            }
                        }, trigger: 'change' }
                ]
            }
        };
    },
    methods: {
        createGroup() {
            this.createDialogVisible = true;
        },

        checkChat(count) {
            this.active = count;
            this.GroupName=count.groupName;
            this.$router.push({ path: '/Main/littleGroupChats/chat', query: { count: count} });
        },

        async initGroupList() {
            try {
                this.loading = true;
                const response = await getGroupList();

                if (response.data.message === "成功") {
                    this.grouplist = response.data.data || [];
                    this.$message.success("获取群组列表成功");
                } else {
                    this.$message.error("获取群组列表失败");
                }
            } catch (error) {
                console.error('Error during login:', error);
                this.$message.error("获取群组列表失败，请稍后再试");
            } finally {
                this.loading = false;
            }
        },

        handleAvatarChange(file) {
            this.createGroupForm.picture = file.raw;
            this.createGroupForm.pictureUrl = URL.createObjectURL(file.raw);
        },

        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.createGroupForm.pictureUrl = '';
            this.createGroupForm.picture = null;
        },

        async submitCreateGroup() {
            this.$refs.createGroupForm.validate(async (valid) => {
                if (valid) {
                    try {
                        const formData = new FormData();
                        if (this.createGroupForm.picture) {
                            formData.append('groupName', this.createGroupForm.groupName);
                            formData.append('picture', this.createGroupForm.picture);
                        } else {
                            this.$message.error('请上传群组头像');
                            return;
                        }

                        const response = await createGroup(formData);
                        if (response.data.message === "成功") {
                            this.$message.success('群聊创建成功');
                            this.createDialogVisible = false;
                            await this.initGroupList();
                        } else {
                            this.$message.error(response.data.message || '群聊创建失败');
                        }
                    } catch (error) {
                        console.error('创建群聊失败:', error);
                        this.$message.error('群聊创建失败');
                    }
                }
            });
        },

        async searchGroups() {
            if (!this.searchGroupId) {
                this.$message.warning('请输入群组ID');
                return;
            }

            this.searchLoading = true;
            this.hasSearched = true;

            try {
                const response = await searchGroupo({
                    groupId: this.searchGroupId,
                });
                if (response.data.message === "成功") {
                    this.searchGroup = response.data.data;
                } else {
                    this.searchGroup = null;
                    this.$message.warning('未找到匹配的群组');
                }
            } catch (error) {
                console.error('搜索群组失败:', error);
                this.$message.error('搜索群组失败');
                this.searchGroup = null;
            } finally {
                this.searchLoading = false;
            }
        },

        joinGroup() {
            this.joinDialogVisible = true;
            this.resetSearch();
        },

        resetSearch() {
            this.searchGroupId = '';
            this.searchGroup = null;
            this.hasSearched = false;
        },

        isGroupJoined(groupId) {
            return this.grouplist.some(g => g.groupId === groupId);
        },

        async quitGroup(groupId){
            try {
                const response = await outGroup({
                    GroupId: groupId
                });
                console.log(response.data);
                if (response.data.message === "成功") {
                    this.$message.success('成功退出群聊');
                    this.joinDialogVisible = false;
                    await this.initGroupList();
                    this.active = null;
                } else {
                    this.$message.error(response.data.message || '退出群聊失败');
                }
            } catch (error) {
                console.error('加入群聊失败:', error);
                this.$message.error('加入群聊失败');
            }
        },

        async handleJoinGroup(groupId) {
            try {
                const response = await joinGroup({
                    GroupId: groupId
                });
                console.log(response.data);
                if (response.data.message === "成功") {
                    this.$message.success('成功加入群聊');
                    this.joinDialogVisible = false;
                    await this.initGroupList();
                } else {
                    this.$message.error(response.data.message || '加入群聊失败');
                }
            } catch (error) {
                console.error('加入群聊失败:', error);
                this.$message.error('加入群聊失败');
            }
        }
    },
    created() {
        this.initGroupList();
    }
};
</script>

<style scoped>
.main-container {
    display: flex;
    width: 100%;
    height: 550px;
    gap: 16px;
    margin-top: 16px;
}

/* 左侧群组列表样式 */
.chat-sidebar {
    width: 260px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
}

.sidebar-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #e8e8e8;
}

.sidebar-header h3 {
    margin: 0;
    color: #303133;
}

.sidebar-actions {
    display: flex;
    gap: 8px;
}

.group-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
}

.group-item {
    display: flex;
    align-items: center;
    padding: 12px;
    border-radius: 8px;
    margin-bottom: 8px;
    text-decoration: none;
    color: #303133;
    transition: all 0.3s;
}

.group-item:hover {
    background-color: #f5f7fa;
}

.active-group {
    background-color: #ecf5ff;
}

.group-avatar {
    border: 2px solid #e8f0fe;
}

.group-item-info {
    margin-left: 12px;
    display: flex;
    flex-direction: column;
}

.group-name {
    font-weight: 500;
    font-size: 14px;
}

.group-status {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
}

.status-dot {
    height: 8px;
    width: 8px;
    border-radius: 50%;
    margin-right: 5px;
}

.status-dot.online {
    background-color: #34a853;
}

.empty-groups {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #909399;
    padding: 20px;
}

.empty-groups i {
    font-size: 40px;
    margin-bottom: 16px;
    color: #e0e0e0;
}

/* 主聊天区域样式 */
.chat-main {
    flex: 1;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

/* 右侧信息面板样式 */
.chat-info {
    width: 250px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
}

.info-header {
    padding: 16px;
    border-bottom: 1px solid #e8e8e8;
}

.info-header h3 {
    margin: 0;
    color: #303133;
}

.group-info-content {
    flex: 1;
    padding: 20px;
    display: flex;
    flex-direction: column;
}

.group-profile {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
}

.group-avatar-large {
    margin-bottom: 16px;
    border: 3px solid #e8f0fe;
}

.group-title {
    margin: 0 0 8px 0;
    font-size: 18px;
    color: #303133;
}

.group-id, .group-owner {
    color: #606266;
    font-size: 14px;
    margin-bottom: 4px;
}

.group-actions {
    margin-top: 16px;
    display: flex;
    justify-content: center;
}

.empty-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
}

.empty-info i {
    font-size: 50px;
    margin-bottom: 16px;
    color: #e0e0e0;
}

/* 搜索结果样式 */
.group-item-search {
    display: flex;
    align-items: center;
    padding: 16px;
    border-radius: 8px;
    background-color: #f5f7fa;
    margin-bottom: 12px;
}

.group-info-search {
    margin-left: 16px;
    flex: 1;
}

.group-info-search h4 {
    margin: 0 0 4px 0;
    font-size: 16px;
}

.group-info-search p {
    margin: 2px 0;
    color: #606266;
    font-size: 14px;
}

.join-btn {
    margin-left: auto;
}

.loading-container, .empty-search-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: #909399;
}

.loading-container i, .empty-search-result i {
    font-size: 40px;
    margin-bottom: 16px;
}

/* 头像上传样式 */
.avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
}

.avatar-uploader:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
点击对应群聊后不进入聊天页面
